package com.qf.commons.core.listener;

import org.slf4j.MDC;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * 日志框架 MDC配置的监听器
 * author Ken
 * create_time 2022/11/21
 */
public class LogMDCConfigListener implements GenericApplicationListener {
    /**
     * 当前需要监听什么事件
     * @param eventType the event type (never {@code null})
     * @return
     */
    @Override
    public boolean supportsEventType(ResolvableType eventType) {
        //判断当前监听到的事件 是否为 ApplicationEnvironmentPreparedEvent类型
        //如果是的话，该方法返回true，如果该方法返回true，就会执行onApplicationEvent方法
        return eventType.isAssignableFrom(ApplicationEnvironmentPreparedEvent.class);
    }

    /**
     * 监听到了相关的事件
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        //读取微服务的名称 ？？？？
        ApplicationEnvironmentPreparedEvent environmentPreparedEvent = (ApplicationEnvironmentPreparedEvent) event;
        //获取SpringBoot的本地环境
        ConfigurableEnvironment environment = environmentPreparedEvent.getEnvironment();
        //读取配置 微服务的名称
        String appName = environment.getProperty("spring.application.name");
        System.out.println("微服务的名字：" + appName);

        //放入MDC
        MDC.put("logPath", appName);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 19;
    }
}
